<!-- html -->
<template>
  <el-dialog :title="title" v-model="open" width="500px" append-to-body>
    <el-form ref="areaRef" :model="form" :rules="rules"  label-width="80px">
      <el-form-item label="区域名字" prop="name">
        <el-input v-model="form.name" placeholder="请输入省市区名字" />
      </el-form-item>
      <el-form-item label="类型" prop="category">
        <el-select v-model="form.category" placeholder="请选择类型">
          <el-option
            v-for="dict in area_type"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="所属区域" prop="parentId">
        <el-tree-select
          v-model="form.parentId"
          :data="areaOptions"
          :props="{ value: 'id', label: 'name', children: 'children' }"
          value-key="id"
          placeholder="请选择父级区域，0标识无父级区域"
          check-strictly
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<!-- 
    ts 
   setup  支持setup语法糖
-->
<script lang="ts" setup>
import { reactive, ref,watch, toRefs,defineEmits, getCurrentInstance } from "vue";

//获取当前组件的实力对象
let proxy = getCurrentInstance()

//接收父组件的事件
const emits = defineEmits(['cancelBox','submitForm'])

//接收父组件传入的参数
let props = defineProps({
  title: {
    type: String,
    default: null,
  },
  open: {
    type: Boolean,
    default: false,
  },
  areaOptions:{
    type:Array,
    default:[]
  },
  area_type:{
    type:Array,
    default:[]
  },
  formInfo:{
    type:Object,
    default:null
  }
});

//抽离父组件传入的参数，解析成要的属性
let { title, open } = toRefs(props);

//定义表单参数
let form =reactive({
    id: null,
    name: null,
    category: null,
    sort: null,
    parentId: null
})

let rules=reactive({
    name: [
      { required: true, message: "省市区名字不能为空", trigger: "blur" }
    ],
    category: [
      { required: true, message: "类型不能为空", trigger: "change" }
    ],
    parentId: [
      { required: true, message: "父级区域，0标识无父级区域不能为空", trigger: "change" }
    ]
  })

//定义函数-提交表单
const submit=()=>{
    proxy.refs.areaRef.validate(valid => {
    if (valid) {
        emits('submitForm',form)
    }
  });
}


//定义函数-取消表单
const cancel=()=>{
    //调用父组件方法
    emits('cancelBox')
} 

//监听器
watch(()=>props.formInfo,(newValue,oldValue)=>{
    //深克隆
      form = reactive( JSON.parse(JSON.stringify(newValue)) )
    },{deep:true})

</script>
<!-- css样式 -->
<style scoped>
</style>